//
//  CHImageScanView.m
//  ChildHoodStemp
//
//  Created by hang on 13-10-25.
//
//


#import <QuartzCore/QuartzCore.h>
#import "CHImageScanView.h"
#import "ChildHoodMessage.h"
#import "UIUtil.h"
#import "MicroDef.h"
#import "MBProgressHUD+WZ.h"
#import "IMFowardController.h"
#import "WZNavigationController.h"

//#import "CHResourceService.h"
//#import "ChildHoodPost.h"
#import "Snsp.pb.h"
#import "CHLongPress.h"

#import "ChildHoodService.h"
#import "ChildHoodUser.h"
#define ImageWidth      300.0f

@interface CHImageScanView ()<UIScrollViewDelegate,UIActionSheetDelegate,MutiltimediaViewDelegate>
{
//    NSInteger _indexNum;
    UIView                  *_fullscreenView;
   
    UITapGestureRecognizer  *_tapGestureRecognizer;
    NSInteger               _index;
    UILabel*                _label;
    NSMutableArray*         _imageMessageArray;
    
    
}
@end

@implementation CHImageScanView
@synthesize imageArray;
@synthesize chMessages;


- (void)dealloc

{
    
//    NSLog(@"chimagscanview");
}

+ (instancetype)sharedInstance
{
    return [[self alloc] init];
}
- (void)loadView
{
    self.view = [[UIView alloc] init];
    self.view.frame = [UIScreen mainScreen].bounds;
    self.view.backgroundColor = [UIColor blackColor];
    self.automaticallyAdjustsScrollViewInsets = NO;
    UIViewAutoresizing autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
    
    _fullscreenView = [[UIView alloc] init];
    [_fullscreenView setAutoresizingMask:autoresizingMask];
    _fullscreenView.backgroundColor = [UIColor blackColor];
    _tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(backTapMethod:)];
    [_fullscreenView addGestureRecognizer:_tapGestureRecognizer];
    [self.view addSubview:_fullscreenView];
    
    
    _sourceMutilImageView = [[MutiltimediaView alloc] initWithFrame:CGRectZero];
    _sourceMutilImageView.backgroundColor = ClearColor;
    CHLongPress* longPress = [[CHLongPress alloc] initWithTarget:self action:@selector(longPressToActionMenu:) userInfo:nil];
    _sourceMutilImageView.showProgress = YES;
    _sourceMutilImageView.multiDelegate = self;
    [_fullscreenView addGestureRecognizer:longPress];
    
    
    _label = [[UILabel alloc]init];
    UISwipeGestureRecognizer *recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeToRight:)];
    [recognizer setDirection:(UISwipeGestureRecognizerDirectionRight)];
    [_fullscreenView addGestureRecognizer:recognizer];
    
    UISwipeGestureRecognizer *recognizer1 = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeFromRight:)];
    [recognizer1 setDirection:(UISwipeGestureRecognizerDirectionLeft)];
    [_fullscreenView addGestureRecognizer:recognizer1];
    
    
    
    _sourceMutilImageViewBackup = [[MutiltimediaView alloc] initWithFrame:CGRectZero];
    _sourceMutilImageViewBackup.backgroundColor = ClearColor;
    _sourceMutilImageViewBackup.showProgress=YES;
    _sourceMutilImageViewBackup.multiDelegate = self;
//    UIView *keyWindow = [UIApplication sharedApplication].keyWindow;
//    CGRect rr = keyWindow.bounds;
//    rr.origin.y = keyWindow.bounds.size.height - 30;
//    rr.size.height = 20;
//    _label.backgroundColor = [UIColor clearColor];
//    _label.text = @"";
//    _label.frame =rr;
//    _label.textColor = [UIColor whiteColor];
//    _label.textAlignment = NSTextAlignmentCenter;
    _imageMessageArray = [[NSMutableArray alloc]init];
    
    
    [_fullscreenView addSubview:_sourceMutilImageViewBackup];
    _sourceMutilImageViewBackup.backgroundColor = BlackColor;
    
    [_fullscreenView addSubview:_sourceMutilImageView];
    _sourceMutilImageView.backgroundColor = BlackColor;
    
//    [_fullscreenView addSubview:_label];

}


//- (void)hideFileUriImg{
//    //[[NSNotificationCenter defaultCenter ] removeObserver:self name:@"HideFileUriImg" object:nil];
//    _fileUriImg.hidden = YES;
//}
//

- (void)showImgWithIndexPath:(NSIndexPath *)indexPath
{

    
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
//    [keyWindow addSubview:self.view];
    [keyWindow.rootViewController addChildViewController:self];
    [keyWindow.rootViewController.view addSubview:self.view];
    [_fullscreenView setFrame:[keyWindow bounds]];
    //[fileUriImg removeFromSuperview];
    [_imageMessageArray removeAllObjects];
    
    CGRect rect = [_fullscreenView bounds];
    _sourceMutilImageView.frame = rect;
    rect.origin.x = -rect.size.width;
    _sourceMutilImageViewBackup.frame = rect;
    
        [_fullscreenView setAlpha:0.0f];
        [UIView animateWithDuration:0.3 animations:^{
            [_fullscreenView setAlpha:1.0f];
        } completion:^(BOOL finished) {
    
        }];
    _index = 0;
    
    
    for(NSInteger i = 0; i< self.chMessages.count; i++){
        ChildHoodMessage* obj = [self.chMessages objectAtIndex:i];
        if(obj.messageType == SNSPMaterialTypeKImage){
            [_imageMessageArray addObject:obj];
        }
        
        if(i == indexPath.row){
            _index = _imageMessageArray.count -1;
            [_sourceMutilImageView showImageWithMessage:obj];
        }
    }
    if(_index < 0)_index = 0;
    [_fullscreenView setAlpha:1.0f];

}



-(void)showImage:(NSInteger)index
{
    [_fullscreenView bringSubviewToFront:_label];
    if(self.imageArray)
    {
         [_sourceMutilImageView setImage:[self.imageArray  objectAtIndex:_index]];
        _label.text = [NSString stringWithFormat:@"%zd/%zd", _index+1, self.imageArray.count];
//        _label.backgroundColor = RedColor;
    }
    
}


-(void)showImage
{
    
    _fullscreenView.hidden = NO;
    _index = 0;
    
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    [keyWindow addSubview:self.view];
    [keyWindow.rootViewController addChildViewController:self];
    _fullscreenView.frame = keyWindow.bounds;
    if(self.imageArray)
    {
        [_sourceMutilImageView setFrame:[_fullscreenView bounds]];

        CGRect rect = [_fullscreenView bounds];
        [self showImage:_index];
        rect.origin.x = -rect.size.width;
        _sourceMutilImageViewBackup.frame = rect;
 
        
        [_fullscreenView setAlpha:0.0f];
        
        [UIView animateWithDuration:0.3 animations:^{
            [_fullscreenView setAlpha:1.0f];

        } completion:^(BOOL finished) {
            
        }];

    }
    
}

- (void)hideImg
{
    self.imageArray = nil;
    self.chMessages = nil;
    _label.text = @"";
    _index = 0;
    [UIView animateWithDuration:0.3 animations:^{
        [_fullscreenView setAlpha:0.0f];
    } completion:^(BOOL finished) {
        [self.view removeFromSuperview];
        [self removeFromParentViewController];
    }];
}

-(void)backTapMethod:(id)sender
{
    if ([_tapGestureRecognizer state] == UIGestureRecognizerStateEnded) {
        [self hideImg];
    }
}


-(void)longPressToActionMenu:(CHLongPress*)longpress
{
    if (longpress.state == UIGestureRecognizerStateBegan) {
        if(self.imageArray)return;
        if ([[NSFileManager defaultManager] contentsAtPath:_sourceMutilImageView.localFilePath].length < _sourceMutilImageView.childMessage.fileLenth.longLongValue) {
            return;
        }
        UIActionSheet* longAction = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"转发",@"保存到手机", nil];
        [longAction showInView:_fullscreenView];
    }else{
        return;
    }
}

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    switch (buttonIndex) {
        case 0:
        {
            [ChildHoodService defaultService].imgLocalFilePath = _sourceMutilImageView.localFilePath;
            [ChildHoodService defaultService].fileModel = nil;
            
            [self fowardImage];
//            [self.imageScanDelegate fowardImage];
//            if ([self.imageScanDelegate respondsToSelector:@selector(fowardImage)]) {
//            }
        }
        break;
          case 1:
        {
            NSString *filePath = _sourceMutilImageView.localFilePath;
            UIImage* img = [UIImage imageWithContentsOfFile:filePath];
            if(img != nil){
                UIImageWriteToSavedPhotosAlbum(img, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
            }

        }
        default:
            break;
    }
//    if (buttonIndex == 0) {
//        //发送给朋友
//        NSString* filePath = [_sourceMutilImageView localFileName:NO];
//        UIImage* img = [UIImage imageWithContentsOfFile:filePath];
//        if(img == nil){
//            NSString* filePath = [_sourceMutilImageView localFileName:YES];
//            img = [UIImage imageWithContentsOfFile:filePath];
//        }
//        UIImageWriteToSavedPhotosAlbum(img, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
//    }
}
- (void)fowardImage
{
    IMFowardController *foward = [[IMFowardController alloc] init];
    WZNavigationController *nav = [[WZNavigationController alloc] initWithRootViewController:foward];
    [self presentViewController:nav animated:YES completion:nil];
    [self hideImg];
}
-(void)scrollRight
{
    [self handleSwipeToRight:nil];
}
-(void)scrollLeft
{
    [self handleSwipeFromRight:nil];
}
-(void)handleSwipeToRight:(id)sender{

    
    if(self.imageArray)
    {
        
        if(_index <= 0)return;
        
        if(_index > 0)_index--;
        if(_index <0)_index = 0;
       
        id old = _sourceMutilImageViewBackup;
        _sourceMutilImageViewBackup = _sourceMutilImageView;
        _sourceMutilImageView = old;
        
        
        [self showImage:_index];
       }else if(self.chMessages){
           if(_index <= 0)return;
           
           if(_index > 0)_index--;
           if(_index <0)_index = 0;
           
           id old = _sourceMutilImageViewBackup;
           _sourceMutilImageViewBackup = _sourceMutilImageView;
           _sourceMutilImageView = old;

           
           ChildHoodMessage* msg = [_imageMessageArray objectAtIndex:_index];
           
           if(msg.messageType == SNSPMaterialTypeKImage)
           {
               [_sourceMutilImageView showImageWithMessage:msg];
               _label.text = [NSString stringWithFormat:@"%zd/%zd", _index+1, _imageMessageArray.count];

           }
       }else{
           return;
       }
    CGRect rect = [_fullscreenView bounds];
    CGRect rect2 = rect;
    rect.origin.x = -rect.size.width;
    [_sourceMutilImageView setFrame:rect];

    CGRect rect0 = rect;
    rect0.origin.x = rect0.size.width;
    [UIView animateWithDuration:.5 animations:^{
        [_sourceMutilImageView setFrame:rect2];
        [_sourceMutilImageViewBackup setFrame:rect0];

    } completion:^(BOOL finished) {
    
    }];
}

-(void)handleSwipeFromRight:(id)sender{
    
    if(self.imageArray)
    {
        
        if(self.imageArray.count -1 <=_index)return;
        if(self.imageArray.count -1 > _index)_index++;

        id old = _sourceMutilImageViewBackup;
        _sourceMutilImageViewBackup = _sourceMutilImageView;
        _sourceMutilImageView = old;
        
        [self showImage:_index];
    }else if(self.chMessages){

        if(_imageMessageArray.count -1 <=_index)return;
        if(_imageMessageArray.count -1 > _index)_index++;
        id old = _sourceMutilImageViewBackup;
        _sourceMutilImageViewBackup = _sourceMutilImageView;
        _sourceMutilImageView = old;
        ChildHoodMessage* msg = [_imageMessageArray objectAtIndex:_index];
        
        if(msg.messageType == SNSPMaterialTypeKImage){
            [_sourceMutilImageView showImageWithMessage:msg];
            _label.text = [NSString stringWithFormat:@"%zd/%zd", _index+1, _imageMessageArray.count];
         
        }
    }else{
        return;
    }
    
    CGRect rect = [_fullscreenView bounds];
    CGRect rect2 = rect;
    rect.origin.x = rect.size.width;
    CGRect rect0 = rect2;
    rect0.origin.x = -rect.size.width;
    [_sourceMutilImageView setFrame:rect];
    
    [UIView animateWithDuration:.5 animations:^{
    
        [_sourceMutilImageViewBackup setFrame:rect0];
        [_sourceMutilImageView setFrame:rect2];
        
    } completion:^(BOOL finished) { 
        
    }];
    
}

- (void)image: (UIImage *) image didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo
{
    NSString *msg = nil ;
    if(error != NULL){
        msg = @"保存图片失败" ;
        [MBProgressHUD showError:msg];
    }else{
        msg = @"保存图片成功" ;
        [MBProgressHUD showSuccess:msg];
    }
    
}
@end
